package com.gitee.webdav.kernel;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.gitee.webdav.HomeStarter;
import com.gitee.webdav.xml.Error;
import com.gitee.webdav.xml.XmlHelper;
import org.smartboot.http.common.enums.HttpStatus;
import org.smartboot.http.server.HttpRequest;
import org.smartboot.http.server.HttpResponse;
import org.smartboot.http.server.HttpServerHandler;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author hongda.li@hand-china.com
 */
public abstract class ResourceReadonlyHandler extends HttpServerHandler {

    protected abstract MethodEnum method();

    protected File path2File(HttpRequest request) {
        String rootPath = HomeStarter.getRootPath();
        return new File(rootPath, URLDecoder.decode(request.getRequestURI(), StandardCharsets.UTF_8));
    }

    protected void writeXml(HttpResponse response, Object data) throws IOException {
        this.writeContentType(response, ContentType.XML.getValue());
        response.write(CharSequenceUtil.bytes(XmlHelper.toXml(data), StandardCharsets.UTF_8));
    }

    protected void writeContentType(HttpResponse response, String contentType) {
        response.setContentType(ContentType.build(contentType, StandardCharsets.UTF_8));
    }

    protected boolean assertFileExists(HttpRequest request, HttpResponse response, File file) throws IOException {
        if (!FileUtil.exist(file) || !FileUtil.isFile(file)) {
            response.setHttpStatus(HttpStatus.NOT_FOUND);
            writeXml(response, Error.of(request.getRequestURI()));
            return false;
        }
        return true;
    }

    protected String readUtf8(HttpRequest request) throws IOException {
        return StrUtil.str(IoUtil.readBytes(request.getInputStream(), false), StandardCharsets.UTF_8);
    }
}
